let model; // 3d 模型

let scene, // 场景
  camera, // 相机
  renderer, // 渲染器
  controls; // 控制器

function initThreeJS() {
  // 创建场景
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x000000);

  const container = document.getElementById("scene-container");
  const aspect = container.clientWidth / container.clientHeight;

  // 创建摄像机
  camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 1000);
  camera.position.set(0, 2, 5);

  // 创建渲染器
  renderer = new THREE.WebGLRenderer({
    antialias: true,
    logarithmicDepthBuffer: true,
  });
  renderer.setSize(container.clientWidth, container.clientHeight);
  renderer.setPixelRatio(window.devicePixelRatio);
  container.appendChild(renderer.domElement);

  // 控制器设置
  controls = new THREE.OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.05;
  controls.minDistance = 1;
  controls.maxDistance = 15;
  controls.target.set(0, 2, 0);
  controls.update();

  // 光照设置
  const ambientLight = new THREE.AmbientLight(0x808080, 0.5);
  scene.add(ambientLight);

  createLight(
    {
      x: -1,
      y: 1,
      z: 5.5,
      intensity: 1,
      distance: 3,
      decay: 1,
    },
    bedroomLight,
    "input_boolean.bedroom_light_1f"
  );

  createLight(
    {
      x: -1,
      y: 1,
      z: 2.5,
      intensity: 1,
      distance: 3,
      decay: 1,
    },
    bedroomLight,
    "input_boolean.bathroom_light_1f"
  );

  createLight(
    {
      x: -0.5,
      y: 1,
      z: -0.5,
      intensity: 1,
      distance: 3,
      decay: 1,
    },
    EntLight,
    "input_boolean.garage_light_1f"
  );
  createLight(
    {
      x: 3,
      y: 1,
      z: 1,
      intensity: 1,
      distance: 3,
      decay: 1,
    },
    KitchenLight,
    "input_boolean.kitchen_light_1f"
  );

  createLight(
    {
      x: 3,
      y: 1,
      z: 5.5,
      intensity: 1,
      distance: 3,
      decay: 1,
    },
    diningRoomLight,
    "input_boolean.dining_room_light_1f"
  );

  createLight(
    {
      x: 8,
      y: 1,
      z: 2.5,
      intensity:2,
      distance: 10,
      decay: 3,
    },
    livingRoomLight,
    "input_boolean.living_room_light_1f"
  );

  createLight(
    {
      x: 12.8,
      y: 1,
      z: 3.0,
      intensity: 1,
      distance: 10,
      decay: 3,
    },
    balconyLight,
    "input_boolean.balcony_light_1f"
  );

  // 创建客厅的窗帘
  livingRoomCurtainAssembly = new THREE.Group();
  createCurtainMore(
    {
      x: 8.5,
      y: 0,
      z: 5.8,
      windowWidth: 5,
      segmentCount: 24,
    },
    livingRoomCurtainAssembly
  );
  scene.add(livingRoomCurtainAssembly);

  // 创建餐厅的窗帘
  restaurantCurtainAssembly = new THREE.Group();
  createCurtainMore(
    {
      x: 3.1,
      y: 0,
      z: 6.9,
      windowWidth: 2.1,
      segmentCount: 24,
    },
    restaurantCurtainAssembly
  );
  scene.add(restaurantCurtainAssembly);
  // 创建卧室的窗帘
  bedroomCurtainAssembly = new THREE.Group();
  createCurtainMore(
    {
      x: -0.5,
      y: 0,
      z: 6.9,
      windowWidth: 2.1,
      segmentCount: 24,
    },
    bedroomCurtainAssembly
  );
  scene.add(bedroomCurtainAssembly);

  // 创建阳台的窗帘
  balconyCurtainAssembly = new THREE.Group();
  createCurtainMore(
    {
      x: 11.8,
      y: 0,
      z: 3.0,
      windowWidth: 5,
      segmentCount: 24,
    },
    balconyCurtainAssembly
  );
  balconyCurtainAssembly.rotation.y = Math.PI / 2;
  scene.add(balconyCurtainAssembly);

  window.addEventListener("resize", onWindowResize);

  // 加载模型（原有代码保持不变）
  // const textureLoader = new THREE.TextureLoader();
  const base64Url = oneFMtlUrl;

  const mtlLoader = new THREE.MTLLoader();
  const mtlString = atob(base64Url);
  const metals = mtlLoader.parse(mtlString);

  const loader = new THREE.OBJLoader();
  loader.setMaterials(metals);
  const base64String = oneFapartmentUrl;

  const byteCharacters = atob(base64String);
  const byteArrays = [];
  for (let offset = 0; offset < byteCharacters.length; offset++) {
    const byteArray = new Uint8Array(1);
    byteArray[0] = byteCharacters.charCodeAt(offset);
    byteArrays.push(byteArray);
  }
  const byteArray = new Uint8Array(byteArrays.length);
  byteArrays.forEach((arr, i) => {
    byteArray[i] = arr[0];
  });

  const blob = new Blob([byteArray], { type: "application/octet-stream" });
  const url = URL.createObjectURL(blob);

  loader.load(
    url,
    (object) => {
      scene.add(object);
      model = object;
      const box = new THREE.Box3().setFromObject(model);
      const boxHelper = new THREE.Box3Helper(box, 0xff0000);
      scene.add(boxHelper);
      setTimeout(() => {
        adjustCameraToFitModel();
      }, 100);
      URL.revokeObjectURL(url);
    },
    (xhr) => {
      console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
    },
    (error) => {
      console.log("加载模型出错：", error);
    }
  );

  // 辅助线
  // const axesHelper = new THREE.AxesHelper(5);
  // scene.add(axesHelper);

  animate();
}

// 俯视视角调整（原有代码保持不变）
function adjustCameraToFitModel() {
  if (!model) return;

  const box = new THREE.Box3().setFromObject(model);
  const size = box.getSize(new THREE.Vector3());
  const center = box.getCenter(new THREE.Vector3());

  const maxDimension = Math.max(size.x, size.y, size.z);
  const container = document.getElementById("scene-container");

  const scaleFactor = 15 / maxDimension;

  model.scale.set(scaleFactor, scaleFactor, scaleFactor);
  box.setFromObject(model);
  box.getSize(size);
  box.getCenter(center);

  setupTopDownView(box, camera, container, center);
  controls.target.set(center.x, center.y, center.z);
  controls.update();
}

function setupTopDownView(box, camera, container, center) {
  const size = box.getSize(new THREE.Vector3());
  // const maxDimension = Math.max(size.x, size.y, size.z);
  const aspect = container.clientWidth / container.clientHeight;

  let distance;
  if (aspect > 1) {
    distance = size.y / (2 * Math.tan((camera.fov * Math.PI) / 360));
  } else {
    distance = size.x / (2 * Math.tan((camera.fov * Math.PI) / 360) * aspect);
  }

  distance *= 7.5;

  camera.position.set(center.x, center.y + distance, center.z);
  camera.lookAt(center.x, center.y, center.z);

  // 双击事件返回俯视视角
  renderer.domElement.addEventListener("dblclick", () => {
    camera.position.set(center.x, center.y + distance, center.z);
    camera.lookAt(center.x, center.y, center.z);
    controls.update();
  });

  camera.near = Math.max(0.1, distance * 0.1);
  camera.far = distance * 5;
  camera.updateProjectionMatrix();
}
